<?php

namespace App\Http\Controllers\Admin;

use App\Http\Models\Permission;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PermissionController extends Controller
{
    //权限列表显示
    public function index(){
        $info = Permission::get()->toArray();//需要将权限名按递归排序 将取出的数据经过函数格式话  所以需要数组格式的
        $info = recursionTree($info,0);
        return view('admin.permission.index',compact('info'));
    }

    //权限列表编辑
    public function edit(Request $request,Permission $permission){

        return view('admin.permission.edit',compact('permission'));
    }
    public function add(Request $request){
        if($request->isMethod('post')){
            //数据验证
            $rules = [
              'ps_name' => 'required',
              'ps_c'    => 'required',
              'ps_a'    => 'required',
              'ps_route'=> 'required'
            ];

            $notices = [
              'ps_name.required' => '权限名称不能为空',
              'ps_c.required' => '控制器名称不能为空',
              'ps_a.required' => '操作方法名称不能为空',
              'ps_route.required' => '路由名称不能为空',
            ];
            $data = $request->all();
            $validator = \Validator::make($data,$rules,$notices);

            if($validator->passes()){
                $ps_plevel = Permission::find($data['ps_pid']);
//            dd($ps_plevel);
            $data['ps_level'] = (string)($ps_plevel['ps_level']+1);
                $res = Permission::create($data);
                if($res){
                    return ['success'=>true];
                }else{
                    return ['success'=>false,'errorinfo'=>'数据添加失败'];
                }

            }else{
                $errorinfo = collect($validator->messages())->implode('0','|');
                return ['success'=>false,'errorinfo'=>$errorinfo];
            }


        }
        $info = Permission::get()->toArray();//需要将权限名按递归排序 将取出的数据经过函数格式话  所以需要数组格式的
        $info = recursionTree($info,0);
        return view('admin.permission.add',compact('info'));
    }
}
